
from aaa import models



def second_rights():
    first_dict = {}
    second_dict = {}
    # filter(permissions__isnull=False)
    x = models.Role.objects.values('id', 'roleName', 'roleDesc', 'permissions__id',
                                                                     'permissions__authName',
                                                                     'permissions__url',
                                                                     'permissions__level',
                                                                     'permissions__pid').distinct()
    for item in x:
        role_id = item['id']
        # print('role_id',role_id)
        level = item['permissions__level']
        id = item['permissions__id']
        pid = item['permissions__pid']
        node = {'id': item['permissions__id'], 'authName': item['permissions__authName'], 'url': item['permissions__url'],
                'level':level,
                'pid':pid}
        if not level:
            first_dict[role_id] = {'id': role_id, 'roleName': item['roleName'], 'roleDesc': item['roleDesc'],
                                   }
        if level == '0':
            if role_id in first_dict:
                first_dict[role_id]['children'].append(node)
            else:
                first_dict[role_id] = {'id':role_id,'roleName':item['roleName'],'roleDesc':item['roleDesc'],'children':[node]}
        #找出角色{1: {'id': 1, 'roleName': '运维', 'roleDesc': 'yunwei'}, 2: {'id': 2, 'roleName': '研发', 'roleDesc': 'yanfa'}}
        # first_dict[role_id] = {'id': role_id, 'roleName': item['roleName'], 'roleDesc': item['roleDesc']}
        #一级权限没有pid，只对二级三级权限操作
        if pid:
            # print('1      second_dict',second_dict)
            #拥有相同pid的二级三级权限归类到(role_id,pid)下，格式：
            '''{
                (1, 8): { #二级菜单
                    'children': [node1,node2]
                }, (1, 7): {
                    'children': [node}]
                }, (1, 4): { #三级菜单
                    'children': [node1,node2]
                }, (2, 7): {
                    'children': [node]
                }
            }'''
            if (role_id,pid) in second_dict:
                #if去重重复的二级菜单
                # print(level, node)
                # print('11      second_dict', role_id,pid)
                # if node in second_dict[role_id,pid]['children']:
                #     continue
                # else:
                    #添加三级菜单
                if level == 2:
                    continue
                else:
                    second_dict[role_id,pid]['children'].append(node)

            else:

                second_dict[role_id,pid] = {'children':[node]}
        # else:
            # first_dict[role_id] = {'id':role_id,'roleName':item['roleName'],'roleDesc':item['roleDesc'],'children':[node]}
    print('------->first_dict',first_dict)
    return first_dict,second_dict

def all_rights():
    role_dict, second_dict = second_rights()
    # menu_list = [1, 2, 3, 5]
    roles_obj = models.Role.objects.all().values('id')
    rids = list(map(lambda i:i['id'],roles_obj))
    third_dict = {}
    third_id_list = []

    # 根据menu_id、二级权限id，把三级权限添加到二级权限下
    for k, v in second_dict.items():
        # {'id': 5, 'authName': '添加客户', 'url': '/users/add/', 'level': '2', 'pid': 4}
        t = v['children'][0]
        # print('xxx', t['id'])
        for i in rids:
            if (i, t['id']) in second_dict:

                # print('11111111111111111',(i,t['id']))
                # print('22222222222222222',k[0])
                third_id_list.append((i, t['id']))
                # 有三级权限才添加
                if i == k[0]:
                    t['children'] = second_dict[(i, t['id'])]['children']

    # 去掉重复的三级权限
    # print(set(third_id_list))
    for item in set(third_id_list):
        del second_dict[item]

    # print('x', second_dict)
    # 根据角色列表、二级权限，把二级权限三级权限添加到各个角色的一级权限下
    for item in second_dict:
        # print(item)
        for i in role_dict:
            if i == item[0]:
                #first_right，一级权限
                for first_right in role_dict[i]['children']:
                    if first_right['id'] == item[1]:
                        # print('111 item',item,x[item],x[item]['children'])
                        # print('first_right',first_right)
                        children = first_right.get('children')
                        rights = second_dict[item]['children']
                        if children:
                            if rights not in children:
                                print('111111111111')
                                first_right['children'].append(rights[0])
                        else:
                            first_right['children'] = rights
    # print('role_dict', role_dict)
    return role_dict

